package ExchangerDemo;

import java.awt.image.DataBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Exchanger;

/**
 * Created with IntelliJ IDEA.
 * User: belict
 * Date: 12/2/13
 * Time: 12:05 PM
 * To change this template use File | Settings | File Templates.
 */
public class Run {
    Exchanger<ArrayList> exchanger = new Exchanger<ArrayList>();
    ArrayList<Integer> arrayFirstList = new ArrayList<Integer>();
    ArrayList<Integer> arraySecondList = new ArrayList<Integer>();

    class FillingLoop implements Runnable {

        FillingLoop() {
            for (int i = 0; i < 5; i++) {
                arrayFirstList.add(i);
            }
        }

        public void run() {
            ArrayList currentList = arrayFirstList;
            try {
                currentList = exchanger.exchange(currentList);
            } catch (InterruptedException ex) { ex.printStackTrace(); }
        }
    }

    class EmptyingLoop implements Runnable {

        EmptyingLoop() {
            for (int i = 0; i < 5; i++) {
                arraySecondList.add(i * -1);
            }
        }

        public void run() {
            ArrayList currentList = arraySecondList;
            try {
                System.out.println("Before exchange + " + currentList);
                currentList = exchanger.exchange(currentList);
                System.out.println("After exchange + " + currentList);
            } catch (InterruptedException ex) { ex.printStackTrace();}
        }
    }

    public static void main(String[] args) {
        Run run = new Run();
        run.start();
    }
    void start() {
        new Thread(new FillingLoop()).start();
        new Thread(new EmptyingLoop()).start();
    }
}
